function [ delta, gamma ] = Greeks( S, V, method, flag, fplot)
%GREEKS Summary of this function goes here
%   Detailed explanation goes here
% This function calculates the Greeks of the option value for a given
% Price vector S, and Option value vector V using the discretized method
% Function also does the following plots
% Price-Option, Price-Delta, Price-Gamma
% flag = 0: Put, flag = 1: Call
% method = 1: Crank-Nicolson, 0: Fully Implicit
% fplot: plot the graphs or not. Default is plot

if nargin < 5
    fplot = 1; end

if flag == 0
    Option = 'Put';
else
    Option = 'Call';
end
if method == 0 
    Method = 'Fully Implicit';
elseif method == 1 
    Method = 'Crank-Nicolson';
else
    Method = 'C-N Rannacher';
end

assert(length(S) == length(V));
N = length(S);
% find dSi+1/2 and dSi-1/2
Si = S(2:end-1);
Si_f = S(3:end);
Si_b = S(1:end-2);
% Sub vector of Option Values
Vi = V(2:end-1);
Vi_f = V(3:end);
Vi_b = V(1:end-2);

dSi_f = Si_f - Si;
dSi_b = Si - Si_b;

delta = zeros(N-2,1);
gamma = zeros(N-2,1);

delta = (Vi_f - Vi_b)./(dSi_f + dSi_b);
gamma = ((Vi_f - Vi)./dSi_f - (Vi - Vi_b)./dSi_b)./((dSi_f + dSi_b)/2);

if fplot
    % Find plot region
    ind1 = find(Si==50);
    ind2 = find(Si==150);
    % Plot vectors
    S1 = S(ind1+1:ind2+1); V1 = V(ind1+1:ind2+1); % +1 because Si was used for indexing
    delta1 = delta(ind1:ind2); gamma1 = gamma(ind1:ind2);
    % Asset-Option Plot
    subplot(1,3,1);
    plot(S1,V1);
    title({['European ',Option, ' Option Value.']; [' Method: ', Method]});
    xlabel('Asset Price');
    ylabel('Option Value');
    grid on
    % Asset-Delta Plot
    subplot(1,3,2);
    %figure
    plot(S1,delta1);
    title({['European ',Option, ' Option Delta.']; [' Method: ', Method]});
    xlabel('Asset Price');
    ylabel('Option Delta');
    grid on
    % Asset-Gamma Plot
    subplot(1,3,3);
    %figure
    plot(S1,gamma1);
    title({['European ',Option, ' Option Gamma.']; [' Method: ', Method]});
    xlabel('Asset Price');
    ylabel('Option Gamma');
    grid on
end

end

